package com.syqc.monitor.ui.text

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.webkit.JavascriptInterface
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.activity.viewModels
import androidx.annotation.Nullable
import androidx.appcompat.app.AppCompatActivity
import autodispose2.androidx.lifecycle.AndroidLifecycleScopeProvider
import autodispose2.autoDispose
import com.syqc.comlib.UserConstant
import com.syqc.comlib.custom.MLoadingDialog
import com.syqc.comlib.entity.ToastEntity
import com.syqc.comlib.utils.setResultTo
import com.syqc.comlib.utils.toast
import com.syqc.monitor.R
import com.syqc.monitor.databinding.DialogEditFastBinding
import com.syqc.monitor.databinding.IncludeSelectSureBinding
import com.syqc.utils.Keys
import com.syqc.utils.UrlUtil


/**
 *@Author Jasper
 *@Time   2021/1/11
 *@Desc   快速编辑
 */
open class EditFastDialog : AppCompatActivity() {

    private lateinit var binding: DialogEditFastBinding
    private lateinit var mSureVB: IncludeSelectSureBinding
    private val mViewModel by viewModels<TextSendViewModel>()
    protected val scopeProvider: AndroidLifecycleScopeProvider by lazy {
        AndroidLifecycleScopeProvider.from(this)
    }
    private val oldUrl by lazy {
        "http://zl.31gps.net:8778/#/?titlebar=false&ip=" + UserConstant.current_ip
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DialogEditFastBinding.inflate(layoutInflater)
        mSureVB = IncludeSelectSureBinding.bind(binding.root)
        setContentView(binding.root)
        initWebSetting()

        binding.mEditWebView.setWebViewClient(webViewClient)
        binding.mEditWebView.setWebChromeClient(webChromeClient)
        binding.mEditWebView.addJavascriptInterface(JsInterAction(), "android")

        mSureVB.tvSure.setText(R.string.hint_close)
        mSureVB.tvSure.setOnClickListener { v -> finish() }

        val newUrl = "${UrlUtil.baseHost()}/msg.html?sessionId=${UserConstant.sessionId}"
        mViewModel.toastObserver().autoDispose(scopeProvider).subscribe(this::toastObserver)
        mViewModel.testLive.observe(this) {
            val url = if (it) {
                newUrl
            } else {
                oldUrl
            }
            binding.mEditWebView.loadUrl(url)
        }
        mViewModel.testUrl(newUrl)
    }

    override fun moveTaskToBack(nonRoot: Boolean): Boolean {
        return super.moveTaskToBack(true)
    }

    private fun initWebSetting() {
        //声明WebSettings子类
        val webSettings: WebSettings = binding.mEditWebView.settings
        //设置自适应屏幕，两者合用
        webSettings.useWideViewPort = true //将图片调整到适合webview的大小

        webSettings.loadWithOverviewMode = true // 缩放至屏幕的大小
        //开启缓存本地
        webSettings.domStorageEnabled = true
        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.javaScriptEnabled = true
        //支持内容重新布局
        webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        //缩放操作
        webSettings.setSupportZoom(true) //支持缩放，默认为true。是下面那个的前提。

        webSettings.builtInZoomControls = true //设置内置的缩放控件。若为false，则该WebView不可缩放

        webSettings.displayZoomControls = false //隐藏原生的缩放控件

        //其它细节操作
        webSettings.allowFileAccess = true //设置可以访问文件

        webSettings.javaScriptCanOpenWindowsAutomatically = true //支持通过JS打开新窗口

        webSettings.loadsImagesAutomatically = true //支持自动加载图片

        webSettings.defaultTextEncodingName = "utf-8" //设置编码格式


        //设置 WebView 字体的大小，默认大小为 16
        webSettings.defaultFontSize = 14
        //设置 WebView 支持的最小字体大小，默认为 8
        webSettings.minimumFontSize = 10
        // 5.1以上默认禁止了https和http混用，以下方式是开启
        webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        //解决图片不显示
        webSettings.blockNetworkImage = false
    }


    private var webViewClient: WebViewClient = object : WebViewClient() {
        //设定加载开始的操作
        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            super.onPageStarted(view, url, favicon)
            binding.seekBarEditWebView.setProgress(0)
            binding.seekBarEditWebView.setVisibility(View.VISIBLE)
        }

        //设定加载结束的操作
        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            binding.seekBarEditWebView.setVisibility(View.GONE)
        }

        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            // 我们这个地方返回false, 并不处理它,把它交给webView自己处理.
            //解决WebView的重定向问题
            return false
        }
    }

    private var webChromeClient: WebChromeClient = object : WebChromeClient() {
        override fun onProgressChanged(view: WebView, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
            binding.seekBarEditWebView.progress = newProgress
        }

        override fun getDefaultVideoPoster(): Bitmap? {
            return if (super.getDefaultVideoPoster() == null) {
                BitmapFactory.decodeResource(resources, R.mipmap.ic_default_error)
            } else super.getDefaultVideoPoster()
        }
    }

    //点击返回上一页面而不是退出浏览器
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && binding.mEditWebView.canGoBack()) {
            binding.mEditWebView.goBack()
            return false
        }
        return super.onKeyDown(keyCode, event)
    }


    override fun onDestroy() {
        if (binding.mEditWebView != null) {
            binding.mEditWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
            binding.mEditWebView.clearHistory()
            (binding.mEditWebView.getParent() as ViewGroup).removeView(binding.mEditWebView)
            binding.mEditWebView.destroy()
        }
        super.onDestroy()
        MLoadingDialog.clear()
    }


    inner class JsInterAction {
        //新指令参数错误时返回
        @JavascriptInterface
        fun sendStateToAndroid(state: String) {
            if (state != "1") {
                runOnUiThread { binding.mEditWebView.loadUrl(oldUrl) }
            }
        }

        //弹窗的复制返回内容
        @JavascriptInterface
        fun callback(content: String?) {
            setResultTo(this@EditFastDialog) {
                putExtra(Keys.INTENT_OTHER, content)
            }
            finish()
        }
    }

    fun isShowLoading(isShow: Boolean) {
        if (isShow) MLoadingDialog.showLoading(this) else MLoadingDialog.dismiss()
    }

    fun toastObserver(entity: ToastEntity) {
        if (entity.toast.isNotEmpty()) {
            toast(entity.toast)
            return
        }
        if (entity.toastId != 0) {
            toast(entity.toastId)
            return
        }
        isShowLoading(entity.isShowLoading)
    }
}